<template>
  <div class="exchange-record">
    <div class="page-header">
      <h1>我的兑换记录</h1>
      <p>查看您的积分兑换历史</p>
    </div>

    <div class="record-content">
      <div class="filter-section">
        <div class="filter-item">
          <label>兑换状态：</label>
          <el-select v-model="filters.status" placeholder="全部状态" clearable @change="loadRecords">
            <el-option label="全部状态" value=""></el-option>
            <el-option label="已完成" value="COMPLETED"></el-option>
            <el-option label="处理中" value="PROCESSING"></el-option>
            <el-option label="已取消" value="CANCELLED"></el-option>
          </el-select>
        </div>
        
        <div class="filter-item">
          <label>兑换时间：</label>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="loadRecords"
          />
        </div>
      </div>

      <div class="records-list" v-loading="loading">
        <div v-if="records.length === 0 && !loading" class="empty-state">
          <i class="el-icon-box"></i>
          <p>暂无兑换记录</p>
          <el-button type="primary" @click="goToExchangeShop">去兑换商品</el-button>
        </div>
        
        <div v-else>
          <div v-for="record in records" :key="record.id" class="record-card">
            <div class="record-header">
              <div class="record-info">
                <span class="record-code">兑换码：{{ record.exchangeCode }}</span>
                <span class="record-date">{{ formatDate(record.exchangeDate) }}</span>
              </div>
              <div class="record-status">
                <el-tag :type="getStatusType(record.status)">
                  {{ getStatusText(record.status) }}
                </el-tag>
              </div>
            </div>
            
            <div class="record-body">
              <div class="product-info">
                <img :src="record.productImage || '/src/assets/logo.png'" :alt="record.productName">
                <div class="product-details">
                  <h4>{{ record.productName }}</h4>
                  <p>{{ record.productDescription }}</p>
                  <div class="exchange-details">
                    <span>数量：{{ record.quantity }}</span>
                    <span>消耗积分：{{ record.pointsSpent }}</span>
                  </div>
                </div>
              </div>
              
              <div class="record-actions">
                <el-button 
                  v-if="record.status === 'COMPLETED' && record.exchangeCode"
                  size="small"
                  @click="copyExchangeCode(record.exchangeCode)"
                >
                  复制兑换码
                </el-button>
                <el-button 
                  v-if="record.expireDate"
                  size="small"
                  type="info"
                  @click="showExpiryInfo(record)"
                >
                  查看有效期
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 有效期信息对话框 -->
    <el-dialog
      title="有效期信息"
      :visible.sync="expiryDialogVisible"
      width="400px"
    >
      <div class="expiry-info" v-if="selectedRecord">
        <p><strong>商品名称：</strong>{{ selectedRecord.productName }}</p>
        <p><strong>兑换码：</strong>{{ selectedRecord.exchangeCode }}</p>
        <p><strong>有效期至：</strong>{{ formatDate(selectedRecord.expireDate) }}</p>
        <p><strong>剩余天数：</strong>{{ getRemainingDays(selectedRecord.expireDate) }}</p>
        <div class="expiry-warning" v-if="getRemainingDays(selectedRecord.expireDate) <= 7">
          <i class="el-icon-warning"></i>
          <span>即将过期，请尽快使用！</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="expiryDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ExchangeRecord',
  data() {
    return {
      loading: false,
      records: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      filters: {
        status: ''
      },
      dateRange: null,
      expiryDialogVisible: false,
      selectedRecord: null
    }
  },
  mounted() {
    this.loadRecords()
  },
  methods: {
    // 加载兑换记录
    async loadRecords() {
      this.loading = true
      try {
        const user = JSON.parse(localStorage.getItem('user'))
        if (!user || !user.id) {
          this.$message.error('请先登录')
          return
        }
        
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          userId: user.id,
          ...this.filters
        }
        
        const response = await request.get('/api/member/exchange/records/page', { params })
        if (response.code === '200') {
          this.records = response.data.records || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '加载兑换记录失败')
        }
      } catch (error) {
        console.error('加载兑换记录失败:', error)
        this.$message.error('加载兑换记录失败')
      } finally {
        this.loading = false
      }
    },
    
    // 分页切换
    handleCurrentChange(page) {
      this.currentPage = page
      this.loadRecords()
    },
    
    // 复制兑换码
    copyExchangeCode(code) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(code).then(() => {
          this.$message.success('兑换码已复制到剪贴板')
        }).catch(() => {
          this.fallbackCopyTextToClipboard(code)
        })
      } else {
        this.fallbackCopyTextToClipboard(code)
      }
    },
    
    // 备用复制方法
    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      try {
        document.execCommand('copy')
        this.$message.success('兑换码已复制到剪贴板')
      } catch (err) {
        this.$message.error('复制失败，请手动复制')
      }
      document.body.removeChild(textArea)
    },
    
    // 显示有效期信息
    showExpiryInfo(record) {
      this.selectedRecord = record
      this.expiryDialogVisible = true
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        'COMPLETED': 'success',
        'PROCESSING': 'warning',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'COMPLETED': '已完成',
        'PROCESSING': '处理中',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN')
    },
    
    // 获取剩余天数
    getRemainingDays(expireDate) {
      if (!expireDate) return 0
      const now = new Date()
      const expire = new Date(expireDate)
      const diffTime = expire - now
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      return Math.max(0, diffDays)
    },
    
    // 跳转到兑换商城
    goToExchangeShop() {
      this.$router.push('/exchange/shop')
    }
  }
}
</script>

<style scoped>
.exchange-record {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 0;
  text-align: center;
}

.page-header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  font-weight: 300;
}

.page-header p {
  font-size: 1.2rem;
  opacity: 0.9;
}

.record-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-item label {
  font-weight: 500;
  white-space: nowrap;
}

.records-list {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.empty-state i {
  font-size: 4rem;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 1.2rem;
  margin-bottom: 20px;
}

.record-card {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: #fafafa;
}

.record-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.record-code {
  font-weight: 600;
  color: #333;
}

.record-date {
  font-size: 0.9rem;
  color: #666;
}

.record-body {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-info {
  display: flex;
  gap: 15px;
  flex: 1;
}

.product-info img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.product-details h4 {
  margin-bottom: 8px;
  color: #333;
}

.product-details p {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 10px;
}

.exchange-details {
  display: flex;
  gap: 20px;
  font-size: 0.9rem;
  color: #666;
}

.record-actions {
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.expiry-info {
  padding: 20px 0;
}

.expiry-info p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.expiry-warning {
  margin-top: 15px;
  padding: 10px;
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 4px;
  color: #856404;
  display: flex;
  align-items: center;
  gap: 8px;
}

.expiry-warning i {
  color: #f39c12;
}

@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .record-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .record-body {
    flex-direction: column;
    gap: 20px;
    align-items: flex-start;
  }
  
  .product-info {
    width: 100%;
  }
  
  .record-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 